//
//  LoginViewController.m
//  Inforcollection
//
//  Created by macbook on 15/12/2.
//  Copyright © 2015年 oceansoft.liw. All rights reserved.
//

#import "LoginViewController.h"
#import "UserData.h"

#import "BaseTabBarController.h"

@interface LoginViewController ()
{
    UIButton*validationBtn;
}
@end

@implementation LoginViewController
-(void)viewDidLoad
{  
    [super viewDidLoad];
   
    [self initViews];
//    [self setNavBarColor:APPNavibackColor];

    [self setContextViewFRam];

}

-(void)initViews
{    
//    [self setNaviBarTitle:@"登录"];
    
//    [self setNaviBarLeftBtn:nil];
    
    self.loginButton.layer.masksToBounds=YES;
    
    self.loginButton.layer.cornerRadius=6.0;
    
    self.loginButton.backgroundColor=[RGB(245, 68, 31)colorWithAlphaComponent:0.8];
    
    [self addIconTextField];

}

-(void)addIconTextField
{
    _ContentView.userInteractionEnabled=YES;
    _userNameTextField=[[IconTextField alloc]initWithFrame:CGRectMake(6, 10,ScreenWidth-42, 40)];
    [_userNameTextField.icon setImage:[UIImage imageNamed:@"用户登录_03"]];
    _userNameTextField.textField.placeholder=@"请输入手机号码";
    [_ContentView addSubview:_userNameTextField];
    _userNameTextField.textField.keyboardType=UIKeyboardTypeNumberPad;
    /*在这里设置用户名密码密码*/
    _passWordTextField=[[IconTextField alloc]initWithFrame:CGRectMake(6, CGRectGetMaxY(_userNameTextField.frame)+8, ScreenWidth-142, 40)];
    [_passWordTextField.icon setImage:[UIImage imageNamed:@"用户登录_06"]];
    _passWordTextField.textField.placeholder=@"请输入验证码";
    [_ContentView addSubview:_passWordTextField];
    _passWordTextField.textField.keyboardType=UIKeyboardTypeNumberPad;
    /*在这里设置手机获取得到的验证码*/
    validationBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    validationBtn.frame=CGRectMake(CGRectGetMaxX(_passWordTextField.frame)+5,CGRectGetMaxY(_userNameTextField.frame)+8, 95, 40);
    
    [validationBtn setTitle:@"验证码获取" forState:0];
    [validationBtn setBackgroundColor:RGB(78, 177, 236)];
    [validationBtn addTarget:self action:@selector(Getvalidation) forControlEvents:UIControlEventTouchUpInside];
    validationBtn.layer.cornerRadius=6.0;
    validationBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [validationBtn setTitleColor:[UIColor whiteColor] forState:0];
    [_ContentView addSubview:validationBtn];
}
- (IBAction)loginClick:(UIButton *)sender
{
    
    
    if ([self checkData])
    {
        NSDictionary *postDict=@{@"phone":self.userNameTextField.textField.text,@"postKey":self.passWordTextField.textField.text};
      
        [MBProgressHUD showMessag:@"正在登录..." toView:self.view];
        
     [[HttpAPI shareHttpAPI]loginWithDict:postDict CallBack:^(NSDictionary *receivedData) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

 if(receivedData!=nil){
        
    if([receivedData[@"code"] integerValue]==200){
    
        if([receivedData[@"status"]integerValue]==0){
        
        [MBProgressHUD showError:receivedData[@"desc"] toView:self.view];
        
        }else{
            
        NSDictionary*diction=receivedData[@"data"];
            
        [[UserData shareUserData] saveUserInfoWith:diction[@"user"]];
            
        [SharedNotifiCenter postNotificationName:isLoginSuccess object:nil];
        
        [SharedNotifiCenter postNotificationName:isLoginSuccessForCollection object:nil];
        
        [SharedNotifiCenter postNotificationName:isLoginSuccesToLoadProductionDetails object:nil];
        //只有登录成功才能跳转到首页
        [self setSaveForUserdata];
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取Main.storyboard中的第2个视图
        BaseTabBarController *BaseNav = [mainStory instantiateViewControllerWithIdentifier:@"BaseTabBarController"];
        //设置窗体的根视图为Storyboard里的视图
        SharedApplication.keyWindow.rootViewController =BaseNav;
        [self.view.window makeToast:@"登录成功"];

        [self dismissViewControllerAnimated:YES completion:^{}];}
    }else{
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [MBProgressHUD showError:@"登录失败" toView:self.view];
    }
}else{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    [MBProgressHUD showError:@"网路错误" toView:self.view];

}
     }];
  }
}

-(BOOL)checkData
{

    if ([self checkTel:self.userNameTextField.textField.text]==NO) {
        return NO;
    }
    
    else if ([[self removeSpaceWithString:self.passWordTextField.textField.text]isEqualToString:@""])
    {
        [self.view makeToast:@"请输入验证码" position:@"center"];
        
        return NO;
    }else if (self.passWordTextField.textField.text.length!=6){
        [MBProgressHUD showError:@"请输入6位验证码" toView:self.view];
        return NO;
    }
    
    return YES;
}
//获取验证吗
-(void)Getvalidation
{
    if ([self checkTel:self.userNameTextField.textField.text]==NO)
    {
        return;
    }else{
    NSDictionary *postDict=@{@"phone":self.userNameTextField.textField.text};
    [MBProgressHUD showMessag:@"正在获取..." toView:self.view];
    
    
    [[HttpAPI shareHttpAPI]getYZMWithDic:postDict CallBack:^(NSDictionary *receivedData) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        if(receivedData !=nil){
        
        if([receivedData[@"status"]integerValue]==1){
            [MBProgressHUD showSuccess:receivedData[@"desc"] toView:self.view];
            [validationBtn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
                __block int timeout=60; //倒计时时间
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                    dispatch_source_set_event_handler(_timer, ^{
                        if(timeout<=0){ //倒计时结束，关闭
                            dispatch_source_cancel(_timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [validationBtn setTitle:@"发送验证码" forState:0];
                                validationBtn.userInteractionEnabled = YES;
                                [validationBtn setTitleColor:[UIColor whiteColor] forState:0];
                                [validationBtn setBackgroundColor:AppNavColor];

                            });
                        }else{
                            int seconds = timeout % 180;
                            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                //设置界面的按钮显示 根据自己需求设置
                               
                                [validationBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:0];
                                validationBtn.userInteractionEnabled= NO;
                                 [validationBtn setTitleColor:AppNavColor forState:0];
                               
                            });
                            timeout--;
                        }
                    });
                    dispatch_resume(_timer);

        }else{
            [MBProgressHUD showError:receivedData[@"desc"] toView:self.view];
        }
        }else{
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

            [MBProgressHUD showError:@"网路错误" toView:self.view];
        }
      }];
    }
}
-(void)setContextViewFRam{
    self.ContentView.backgroundColor=RGB(253, 255, 255);
    self.ContentView.layer.cornerRadius=10.0;
    self.ContentView.layer.borderWidth=0.8;
    
    _userNameTextField.layer.borderWidth=0.4;
    _userNameTextField.layer.cornerRadius=8;
    _userNameTextField.layer.borderColor=[UIColor darkGrayColor].CGColor;
    
    _passWordTextField.layer.borderWidth=0.4;
    _passWordTextField.layer.cornerRadius=8;
    _passWordTextField.layer.borderColor=[UIColor darkGrayColor].CGColor;
}

- (IBAction)forgetPassWordClick:(UIButton *)sender
{
    
    
}
- (IBAction)registerClick:(UIButton *)sender
{
    [self performSegueWithIdentifier:@"toRegisterViewController" sender:nil];
}
-(void)setSaveForUserdata{

    NSMutableDictionary*UserDic=[NSMutableDictionary dictionary];
    [UserDic setValue:[UserData shareUserData].userModel.dbId forKey:@"dbId"];
    [UserDic setValue:[UserData shareUserData].userModel.gridName forKey:@"gridName"];
    [UserDic setValue:[UserData shareUserData].userModel.name forKey:@"name"];
    [UserDic setValue:[UserData shareUserData].userModel.phone forKey:@"phone"];
    [UserDic setValue:[UserData shareUserData].userModel.gridid forKey:@"gridid"];
    [UserDefaults setObject:UserDic forKey:@"用户数据"];
    
    [UserDefaults setObject:[UserData shareUserData].userModel.uploadDataMode  forKey:uploadDataModeStatic];
}

- (BOOL)checkTel:(NSString *)str

{
    if (!str || [str isEqualToString:@""]) {
        [self.view makeToast:@"手机号不能为空"];
        return NO;
    }
    if (str.length != 11) {
        [self.view makeToast:@"手机号必须为11位"];
        return NO;
    }
    
    NSString *regex = @"^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch) {
        [self.view makeToast:@"请输入正确的手机号"];
        
        return NO;
    }
    return YES;
    
}
-(NSString *)removeSpaceWithString:(NSString *)string
{
    NSString *strUrl = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return strUrl;
}
@end
